package cn.edu.guet.controller;

import cn.edu.guet.bean.editor.Badge;
import cn.edu.guet.bean.editor.Comment;
import cn.edu.guet.bean.editor.Option;
import cn.edu.guet.bean.editor.Post;
import cn.edu.guet.service.editor.IComService;
import cn.edu.guet.service.editor.PostBll;
import cn.edu.guet.service.editor.UploadImg;
import cn.edu.guet.util.EmojiChange;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.*;


@Controller
@RequestMapping("html/editor/")
public class EditorController {
    @Autowired
    private UploadImg uploadImg;
    @Autowired
    private PostBll postBll;
    @Autowired
    private IComService comService;

    //测试拦截器，跳转到登录页面
    @GetMapping("login.do")
    public String filterTest(){
        return "login";
    }

    //上传图片
    @ResponseBody
    @PostMapping("upload-img.do")
    public Map uploadimg(MultipartFile file){
        return postBll.uploadImg(file);
    }

    //上传帖子
    @ResponseBody
    @PostMapping("publishPost.do")
    public List<String> publishPost(HttpServletRequest request, String tid, String title, String content, String time, String pstatus,String ldate){
        String userid = (int)request.getSession().getAttribute("userid")+"";
        content = EmojiChange.emojiConverterToAlias(content);
        String point = postBll.selectPointByDay(userid,ldate);//查询当前应加分数
        String pid = postBll.publishPost(tid,title,content,time,pstatus,userid);
        if (!pstatus.equals("0")){//如果不是草稿
            //积分
            postBll.insertGradeByPost(userid, 10, ldate);
        }
        List<String> list = new ArrayList<>();
        list.add(pid);
        list.add(point);
        return list;
    }

    //查看帖子
    @GetMapping("viewPost.do")
    public String viewPost(HttpServletRequest request,String pid){
        System.out.println(pid);
        //通过session获取当前用户的id
        String userid = (int)request.getSession().getAttribute("userid")+"";
        //查询评论
        int p = Integer.valueOf(pid);
        int uid = Integer.valueOf(userid);
        List<Comment> commentList = comService.getFatherCom(p);
        request.setAttribute("commentList",commentList);
        //判断评论是否已被点赞，并返回相应图片地址
        List<Integer> comUpRecordList=new ArrayList<>();
        for (Comment comment:commentList ){
            int comid =comment.getComid();
            //设置表情可读
            String comcontent = comment.getComcontent();
            comment.setComcontent(EmojiChange.emojiConverterUnicodeStr(comcontent));

            List<Comment> childCom =comment.getChildCom();
            for (Comment childcomment:childCom){
                int childcomid= childcomment.getComid();
                //设置表情可读
                String childcomcontent = childcomment.getComcontent();
                childcomment.setComcontent(EmojiChange.emojiConverterUnicodeStr(childcomcontent));

                String child_comid = comService.selectComUpRecord(childcomid,uid);
                int comUpRecord = (child_comid==null?0:Integer.valueOf(child_comid));
                comUpRecordList.add(comUpRecord);
            }
            String father_comid = comService.selectComUpRecord(comid,uid);
            int comUpRecord1 = (father_comid==null?0:Integer.valueOf(father_comid));
            comUpRecordList.add(comUpRecord1);
            request.setAttribute("comUpRecordList",comUpRecordList);
        }

        /*************************************************************************/

        Post post=new Post();
        //查询帖子
        post = postBll.selectPostById(pid);
        if (post!=null){
            String pcontent = post.getPcontent();
            //将帖子的emoji字符转为可读
            post.setPcontent(EmojiChange.emojiConverterUnicodeStr(pcontent));
            request.setAttribute("post",post);
            //通过帖子id以及用户id查询点赞情况并返回对应的图片地址
            String giveupOrNot = postBll.selectGiveupOrNot(pid,userid);
            //注意字符串不能用“=” 还要注意空指针异常,可以换位置也可以判一次空
            if (!pid.equals(giveupOrNot)){
                request.setAttribute("giveup","../../images/editor/giveup1.png");
            }else {
                request.setAttribute("giveup","../../images/editor/giveup2.png");
            }
            //通过id查询是否收藏并返回收藏图片的地址
            String collectOrNot = postBll.selectCollectOrNot(pid,userid);
            if (!pid.equals(collectOrNot)){
                request.setAttribute("collect","../../images/editor/collection1.png");
            }else {
                request.setAttribute("collect","../../images/editor/collection2.png");
            }
            //查询帖子的点赞，收藏数量
            int giveupCon = postBll.selectGiveupCon(pid);
            int collectCon = postBll.selectCollectCon(pid);
            request.setAttribute("giveupCon",giveupCon);
            request.setAttribute("collectCon",collectCon);
            //通过帖子id查用户id
            String useredid = postBll.selectUseridByPid(pid);
            //查询用户已经在商城购买的徽章
            List<Badge> badgelist = postBll.selectBadgeByUser(useredid);
            request.setAttribute("badgelist",badgelist);
            return "html/editor/lookPost";
        }
        //这里要处理空指针报错页面
        return null;
    }

    //跳转到写帖子
    @GetMapping("writePost.do")
    public String writePost(HttpServletRequest request){
        //查询帖子的类型
        List<Option> optionList = postBll.selectSelect();
        request.setAttribute("optionList",optionList);
        return "html/editor/writePost";
    }

    //跳转到修改帖子
    @GetMapping("editPost.do")
    public String editPost(HttpServletRequest request, String pid){
        System.out.println(pid);
        //通过session获取当前用户的id
        String userid = (int)request.getSession().getAttribute("userid")+"";
        Post post=new Post();
        //查询帖子
        post = postBll.selectPostById(pid);
        if (post!=null){//如果用户不匹配那就是恶意访问
            if (!post.getUserid().equals(userid)){
                return "html/editor/protect";
            }
            String pcontent = post.getPcontent();
            //将帖子的emoji字符转为可读
            post.setPcontent(EmojiChange.emojiConverterUnicodeStr(pcontent));
            request.setAttribute("post",post);
            //查询帖子的类型
            List<Option> optionList = postBll.selectSelect();
            request.setAttribute("optionList",optionList);
            return "html/editor/editPost";
        }
        return null;
    }

    //更新修改帖子
    @ResponseBody
    @RequestMapping("updatePost.do")
    public boolean updatePost(HttpServletRequest request, String pid,String tid,String ptitle,String pcontent,String ptime,String pstatus,String ldate){
        //System.out.println(request);
        String userid = (int) request.getSession().getAttribute("userid")+"";
        //查询帖子在数据库中的状态（s1）以及日期（pdate）前端传来的状态为（s2）
        Post post = postBll.selectPostSDByPid(pid);
        String s1 = post.getPstatus();
        String pdate = post.getPtime().substring(0,10);
        String s2 = pstatus;
        if((s1.equals("1") || s1.equals("2")) && (s2.equals("1") || s2.equals("2"))){
            //重复发表即为正常修改，不做任何积分处理
        }else if((s1.equals("1") || s1.equals("2")) && (s2.equals("0"))){
            //正常发表改为草稿，要根据日期找到当日的积分进行减少，对users中的总积分进行减少
            postBll.insertGradeByPost(userid, -10, ldate);
        }else if((s1.equals("0")) && (s2.equals("1") || s2.equals("2"))){
            //原本为草稿如今要发表那就直接正常加积分处理
            postBll.insertGradeByPost(userid, 10, ldate);
        }else{
            //s1.equals("0") && s2.equals("0")
        }
        postBll.updatePost(pid, tid, ptitle, pcontent, ptime, pstatus);
        return true;
    }
    //点赞帖子
    @ResponseBody
    @RequestMapping("giveupPost.do")
    public boolean giveupPost(HttpServletRequest request, String pid,String useredid,String ldate){
        String userid = (int) request.getSession().getAttribute("userid")+"";
        postBll.giveupPost(pid,userid,ldate);
        //积分
        postBll.insertGradeByPost(useredid, 1, ldate);
        return true;
    }
    //删除点赞
    @ResponseBody
    @RequestMapping("deleteGiveup.do")
    public boolean deleteGiveup(HttpServletRequest request, String pid,String useredid){
        String userid = (int) request.getSession().getAttribute("userid")+"";
        //处理积分
        postBll.updateGiveupPoint(useredid, userid, pid);
        //删除点赞记录
        postBll.deleteGiveup(pid,userid);
        return true;
    }

    //收藏帖子
    @ResponseBody
    @RequestMapping("collectPost.do")
    public boolean collectPost(HttpServletRequest request, String pid,String useredid,String ldate){
        String userid = (int)request.getSession().getAttribute("userid")+"";
        postBll.collectPost(userid,pid,ldate);
        //积分
        postBll.insertGradeByPost(useredid, 2, ldate);
        return true;
    }

    //删除收藏
    @ResponseBody
    @RequestMapping("deleteCollection.do")
    public boolean deleteCollection(HttpServletRequest request, String pid,String useredid){
        String userid = (int) request.getSession().getAttribute("userid")+"";
        //处理积分
        postBll.updateCollectPoint( useredid, userid, pid);
        //删除记录
        postBll.deleteCollection(userid,pid);
        return true;
    }

    //上传父评论
    @ResponseBody
    @RequestMapping("submitDiscuss.do")
    public boolean submitDiscuss(HttpServletRequest request, int pid,String comcontent,String comtime){
        int userid = (int) request.getSession().getAttribute("userid");
        int comup = 0;//点赞量
        int fatherid = 0;//父id
        int useredid=0;
        //将comcontent中的emoji表情转为数据库可存储
        comcontent=EmojiChange.emojiConverterToAlias(comcontent);
        postBll.insertfatherDiscuss(pid,userid,comcontent,comtime,comup,fatherid,useredid);
        return true;
    }

    //获取帖子类型的下拉选项
    @ResponseBody
    @RequestMapping("selectSelect.do")
    public List<Option> selectSelect(){
        List<Option> list = postBll.selectSelect();
        return list;
    }

    //
    @ResponseBody
    @RequestMapping("isMyPost.do")
    public boolean isMyPost(HttpServletRequest request,String pid){
        String userid = (int)request.getSession().getAttribute("userid")+"";
        boolean bool = (userid.equals(postBll.selectUseridByPid(pid))?true:false);
        return bool;
    }

    /************************************************************************************/
    //添加评论
    @ResponseBody
    @GetMapping("insertReply.do")
    public String insertReply(HttpServletRequest request,int pid,String comtime,String comcontent,int comup,int fatherid,int useredid){
        int userid = (int) request.getSession().getAttribute("userid");
        Comment comment = new Comment();
        comment.setPid(pid);
        comment.setUserid(userid);
        comment.setComtime(comtime);
        //处理表情为可存入
        comcontent = EmojiChange.emojiConverterToAlias(comcontent);
        comment.setComcontent(comcontent);
        comment.setComup(comup);
        comment.setFatherid(fatherid);
        comment.setUseredid(useredid);
        comService.insertReply(comment);
        return "true";
    }
    //点赞数加一
    @ResponseBody
    @GetMapping("updatecomup.do")
    public boolean updateComUp(HttpServletRequest request,int comid){
        int userid = (int) request.getSession().getAttribute("userid");
        comService.updateComUp(comid,userid);
        return true;
    }
    //点赞数减一
    @ResponseBody
    @GetMapping("deletecomup.do")
    public boolean deleteComUp(HttpServletRequest request,int comid){
        int userid = (int) request.getSession().getAttribute("userid");
        comService.deleteComUp(comid,userid);
        return true;
    }

    //点赞数减一
    @ResponseBody
    @GetMapping("selectUserRole.do")
    public String selectUserRole(HttpServletRequest request){
        int userid = (int) request.getSession().getAttribute("userid");
        return postBll.selectUserRole(userid+"");
    }
}